﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

public partial class Content_Admin_UpdateContent:System.Web.UI.Page
{
	int nCatalogID = -1;
	int nContentID = -1;
	protected void Page_Load(object sender,EventArgs e)
	{
		if(Session[SystemConst.USERIDKEY] == null)
		{
			Response.Write(SysOperation.OpenDialog(
				"你还没有登录，请先登录..."));
			Response.Write("<script>history.back()<script>");
			return;
		}
		
		if(Request.Params["CatalogID"] != null)
		{
			if(Int32.TryParse(Request.Params["CatalogID"].ToString(),out nCatalogID) == false)
			{
				return;
			}
		}
		if(Request.Params["ContentID"] != null)
		{
			ViewState[SystemConst.CONTENTIDKEY] = Request.Params["ContentID"].ToString();
			if(Int32.TryParse(Request.Params["ContentID"].ToString(),out nContentID) == false)
			{
				return;
			}
		}
		if(!Page.IsPostBack)
		{
			if(nContentID > -1)
			{
				BindContentData(nContentID);
			}
		}
		UpdateBtn.Enabled = nContentID > -1 ? true : false;
	}

	private void BindContentData(int nContentID)
	{
		IContent content = new Content();
		SqlDataReader dr = content.GetSingleContent(nContentID);

		bool dltype = true;
		short dpFlag = 0;
		if(dr.Read())
		{
			Name.Text = dr["Name"].ToString();
			tbDesn.Text = dr["Desn"].ToString();
			dltype = Boolean.Parse(dr["Type"].ToString().ToLower());
			dpFlag = short.Parse(dr["dpFlag"].ToString());
			ViewState[SystemConst.CONTENTINFOIDKEY] = dr["ContentInfoID"].ToString();
		}
		dr.Close();

		///0:普通内容
		///1:链接内容
		dlType.SelectedValue = dltype ?
			((int)EContentUrl.Content).ToString() :
			((int)EContentUrl.Url).ToString();
		///如果是普通内容
		if(dltype == true)
		{
			tbDesn.TextMode = TextBoxMode.MultiLine;
			tbDesn.Height = SystemConst.TEXTBOXMUTLILINEHEIGHT;

			///如果已经存在文档
			if(dpFlag > 0)
			{
				cbDocument.Visible = cbDocument.Checked
					= cbDocument.Enabled = true;
				///显示已经存在的文档
				BindDocumentData(nContentID);
			}
			else
			{   ///不存在文档，则可以添加新的附件和图片
				cbDocument.Visible = cbDocument.Enabled = true;
				cbDocument.Checked = false;
			}
			pFile.Visible = cbDocument.Checked;
		}
		else
		{
			tbDesn.TextMode = TextBoxMode.SingleLine;
			tbDesn.Height = SystemConst.TEXTBOXSINGLEHEIGHT;
			cbDocument.Visible = cbDocument.Enabled 
				= pFile.Visible = false;
		}
	}

	private void BindDocumentData(int nContentID)
	{
		IDocument doc = new Document();
		SqlDataReader dr = doc.GetDocumentByContent(nContentID);

		DocView.DataSource = dr;
		DocView.DataBind();
		dr.Close();

		DocView.Visible = DocView.Rows.Count > 0 ? true : false;
	}

	protected string FormatContentdpFlag(short sdpFlag)
	{
		switch(sdpFlag)
		{
			case 1:
				///"附件";
				return "~/Images/Attch.gif";
			case 2:
				///"图片";
				return "~/Images/pic.gif";
			default:
				///"未知状态";
				return "~/Images/unknown.gif";
		}
	}

	protected void Btn_Command(object sender,CommandEventArgs e)
	{
		string sCmdName = e.CommandName.ToLower();
		if(SysOperation.StringNullChecked(sCmdName) == false)
		{
			return;
		}
		switch(sCmdName)
		{
			case "add":
				{
					UpdateContent();					
					break;
				}
			case "return":
				{
					Response.Redirect("~/Content/Admin/ContentManage.aspx?CatalogID="
						+ nCatalogID.ToString());
					break;
				}
			default: break;
		}
	}

	private void UpdateContent()
	{
		IContent content = new Content();
		///修改内容
		try
		{
			content.UpdateContent(nContentID,Name.Text.Trim(),tbDesn.Text.Trim());
			Response.Write(SysOperation.OpenDialog(
				SysInfomation.UPDATE_DATA_SUCESS + " 你还可以修改、或添加该内容的附件或图片。"
				));
		}
		catch(Exception ex)
		{
			Server.Transfer(SysOperation.FormatErrorPageUrl(
				SysOperation.FormatErrorUrl(Request.RawUrl),ex.Message),
				false);
		}	
	}
	protected void cbDocument_CheckedChanged(object sender,EventArgs e)
	{
		DocView.Visible = fuFile.Visible = fuFile.Enabled
			= btnUpload.Visible = btnUpload.Enabled
			= pFile.Visible = cbDocument.Checked;
	}
	protected void btnUpload_Click(object sender,EventArgs e)
	{
		if(fuFile.HasFile == false || ViewState[SystemConst.CONTENTIDKEY] == null)
		{
			Response.Write(SysOperation.OpenDialog(
					"数据为空，不能上载所选择的文件")
				);
			return;
		}

		string tfName = fuFile.PostedFile.FileName;
		string fileName = SysOperation.CreateFileNameByDateTime()
			+ tfName.Substring(tfName.LastIndexOf("."));

		string fullfilePath = Server.MapPath("../../Files/" + fileName);
		if(File.Exists(fullfilePath) == true)
		{
			Response.Write(SysOperation.OpenDialog(
				"你上载的文件" + fileName + "已经存在，不能上载所选择的文件")
				);
			return;
		}

		try
		{   ///上载文件
			fuFile.SaveAs(fullfilePath);

			///添加文档信息
			IDocument doc = new Document();
			doc.AddDocument(tbDocName.Text,
				"Files/" + fileName,fuFile.PostedFile.ContentType,
				Int32.Parse(ViewState[SystemConst.CONTENTINFOIDKEY].ToString()),
				short.Parse(rbFileType.SelectedValue));

			///修改内容的附加信息
			IContentInfo contentInfo = new ContentInfo();
			contentInfo.UpdatedpFlag(Int32.Parse(ViewState[SystemConst.CONTENTINFOIDKEY].ToString()),
				short.Parse(rbFileType.SelectedValue));

			///显示附件和图片信息
			BindDocumentData(Int32.Parse(ViewState[SystemConst.CONTENTIDKEY].ToString()));
		}
		catch(Exception ex)
		{
			Server.Transfer(SysOperation.FormatErrorPageUrl(
				SysOperation.FormatErrorUrl(Request.RawUrl),ex.Message),
				false);
		}
	}
	
	protected void DocView_RowDeleting(object sender,GridViewDeleteEventArgs e)
	{
		///
	}
	protected void DocView_RowCommand(object sender,GridViewCommandEventArgs e)
	{
		if(e.CommandName.ToString() == "delete")
		{
			///读取删除附件或图片的信息
			IDocument doc = new Document();
			int nDocumentID = Int32.Parse(e.CommandArgument.ToString());
			SqlDataReader dr = doc.GetSingleDocument(nDocumentID);
			int nContentInfoID = -1;
			string sUrl = "";
			if(dr.Read())
			{
				sUrl = dr["Url"].ToString();
				nContentInfoID = Int32.Parse(dr["ContentInfoID"].ToString());
			}
			dr.Close();

			if(nContentInfoID <= 0 || ViewState[SystemConst.CONTENTIDKEY] == null)
			{
				Response.Write(SysOperation.OpenDialog(
						"数据为空，不能删除所选择的文件")
					);
				return;
			}

			///设置新的dpFlag标志
			SqlDataReader drdoc = doc.GetDocumentByContent(
				Int32.Parse(ViewState[SystemConst.CONTENTIDKEY].ToString()));
			EPictureAttachment dpFlag = EPictureAttachment.Normal;
			while(drdoc.Read())
			{
				if(drdoc["ID"].ToString() != nDocumentID.ToString())
				{
					dpFlag |= (EPictureAttachment)short.Parse(drdoc["dpFlag"].ToString());
				}
			}
			drdoc.Close();

			///更新dpFlag标志
			IContentInfo contentInfo = new ContentInfo();
			try
			{
				contentInfo.UpdatadpFlagDelete(nContentInfoID,(short)dpFlag);

				///删除选择的附件
				doc.DeleteDocument(nDocumentID);
			}
			catch(Exception ex)
			{
				Server.Transfer(SysOperation.FormatErrorPageUrl(
					SysOperation.FormatErrorUrl(Request.RawUrl),ex.Message),
					false);
			}
			string fullfilePath = Server.MapPath("../../" + sUrl);
			if(File.Exists(fullfilePath) == false)
			{
				Response.Write(SysOperation.OpenDialog(
					"要删除的文件：" + sUrl + "不存在。请检查文件是否被意外删除。")
				);
				return;
			}

			try
			{
				File.Delete(fullfilePath);
				///重新显示内容的附件和图片
				BindDocumentData(
					Int32.Parse(ViewState[SystemConst.CONTENTIDKEY].ToString()));
			}
			catch(Exception ex)
			{
				Server.Transfer(SysOperation.FormatErrorPageUrl(
					SysOperation.FormatErrorUrl(Request.RawUrl),ex.Message),
					false);
			}
		}
	}

	protected void DocView_RowDataBound(object sender,GridViewRowEventArgs e)
	{
		ImageButton deleteBtn = (ImageButton)e.Row.FindControl("DeleteBtn");
		if(deleteBtn != null)
		{
			deleteBtn.Attributes.Add("onclick","return confirm('你确定要删除所选择的数据吗?');");
		}
	}
}
